/**
 * 
 */
package lastfmbaseball.core;

import java.util.*;

/**
 * @author DanBress
 * 
 */
public class HalfInning
{
	private Inning inning;
	private InningType inningType;
	private List<AtBat> atBats = new ArrayList<AtBat>(5);

	public HalfInning(Inning inning, InningType inningType)
	{
		this.inning = inning;
		this.inningType = inningType;
	}

	public void addAtBat(AtBat atBat)
	{
		atBats.add(atBat);
	}

	public List<BaseRunner> getBaseRunners()
	{
		List<BaseRunner> baseRunners = new ArrayList<BaseRunner>();

		if (atBats.size() > 0)
		{
			AtBat atBat = atBats.get(atBats.size() - 1);
			List<BaseRunner> lastBaseRunners = atBat.getBaseRunners();
			for (int i = 0; i < lastBaseRunners.size(); i++)
			{
				BaseRunner b = lastBaseRunners.get(i);
				if (b.getBase() != Base.Home && b.getBase() != Base.Batter)
				{
					BaseRunner copy = new BaseRunner(b.getPlayer(),
							b.getBase(), b.getState());
					baseRunners.add(copy);
				}
			}
		}

		return baseRunners;
	}

	public int getHits()
	{
		int hits = 0;
		for (int i = 0; i < atBats.size(); i++)
		{
			AtBat atBat = atBats.get(i);
			if (atBat.getOutsGenerated() == 0)
			{
				hits += 1;
			}
		}

		return hits;
	}

	public Inning getInning()
	{
		return inning;
	}

	public PlayerInGame getLastBatter()
	{
		PlayerInGame lastBatter = null;
		if (atBats.size() > 0)
		{
			AtBat lastAtBat = atBats.get(atBats.size() - 1);

			lastBatter = lastAtBat.getBatter();
		}

		return lastBatter;
	}

	public int getLeftOnBase()
	{
		int leftOnBase = 0;

		if (atBats.size() > 0)
		{
			AtBat lastAtBat = atBats.get(atBats.size() - 1);

			List<BaseRunner> baseRunners = lastAtBat.getBaseRunners();

			for (int i = 0; i < baseRunners.size(); i++)
			{
				BaseRunner br = baseRunners.get(i);
				if (br.getBase() != Base.Batter && br.getBase() != Base.Home
						&& br.getState() == BaseRunnerState.Safe)
				{
					leftOnBase++;
				}
			}
		}

		return leftOnBase;
	}

	public int getNumberOfOuts()
	{
		int numberOfOuts = 0;
		for (int i = 0; i < atBats.size(); i++)
		{
			AtBat atBat = atBats.get(i);
			numberOfOuts += atBat.getOutsGenerated();
		}

		return numberOfOuts;
	}

	public int getRunsScored()
	{
		int runsScored = 0;
		for (int i = 0; i < atBats.size(); i++)
		{
			AtBat atBat = atBats.get(i);
			runsScored += atBat.getRunsScored();
		}

		return runsScored;
	}

	public InningType getType()
	{
		return inningType;
	}

	public String toString()
	{
		return inningType + " of " + inning;
	}
}
